const router = require('koa-router')()
const fs = require('fs')
const path = require('path')
const multer = require('@koa/multer')

router.prefix('/upload')

const storage = multer.diskStorage({ // multer调用diskStorage可控制磁盘存储引擎
    destination:function(req,file,cb){
        let date = new Date()
        let year = date.getFullYear()
        let month = date.getMonth()+1
        let day = date.getDate()
        let dir = "./public/upload/"+year+month+day
        if(!fs.existsSync(dir)){
            fs.mkdirSync(dir,{
                recursive:true
            })
        }
        cb(null,dir)
    },
    filename:function(req,file,cb){
        let fileName = file.fieldname+"-"+Date.now()+path.extname(file.originalname)
        cb(null,fileName)
    }
})

const limits = {
    fields: 10,//非文件字段的数量
    fileSize: 500 * 1024 * 1024,//文件大小 单位 b
    files: 1//文件数量
}
let uploader = multer({storage,limits})

router.post('/img',uploader.single('myfile'), async ctx =>{
    if(ctx.request.file.path){
        let path =  ctx.request.file.path;
        path = ctx.origin + ''+ path.replace('public','');
        ctx.body ={
            code:0,
            data:  path
        }
    }

})
module.exports = router
